﻿using System.Runtime.CompilerServices;
using AlibabaCloud.SDK.Dingtalkexclusive_1_0.Models;

namespace Vote.Project001.Core.Infrastructure
{
    public abstract class SessionValueContainer<TValue>
    {
        protected TValue _value = default;
        private DateTime _lastUpdateTime;
        private object locker=new object();
        protected abstract TimeSpan Duration { get; }

        protected abstract TValue AcquireValue();

        private TValue Check()
        {
            if (DateTime.Now - _lastUpdateTime > Duration)
            {
                lock (locker)
                {
                    if (DateTime.Now - _lastUpdateTime > Duration)
                    {
                        _value = AcquireValue();
                        _lastUpdateTime = DateTime.Now;
                    }
                }
            }

            return _value;
        }

        public TValue Value
        {
            get
            {
                var value = Check();
                return value;
            }
        }

        public static implicit operator TValue(SessionValueContainer<TValue> value)
        {
            return value.Value;
        }
    }
}
